package com.Xht.www.servlet;

//后端响应处理用户注册的请求

import com.Xht.www.dao.UserInfoDAO;
import com.Xht.www.po.UserInfoPO;
import com.Xht.www.util.ValidationUtil;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/register")
public class UserRegisterServlet extends HttpServlet {
    private UserInfoDAO userInfoDAO = new UserInfoDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应格式为 JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String gender = request.getParameter("gender");
        String birthdayStr = request.getParameter("birthday");

        // 构建参数 Map 用于工具类校验
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
        params.put("confirmPassword", confirmPassword);
        params.put("gender", gender);
        params.put("birthday", birthdayStr);

        // 调用工具类进行输入校验
        ValidationUtil.ValidationResult result = ValidationUtil.validateInput("user-register", params);

        if (!result.isSuccess()) {
            out.write("{\"success\": false, \"message\": \"" + result.getMessage() + "\"}");
            out.close();
            return;
        }

        // 参数合法，设置默认值并创建 PO 对象
        String userStatus = "正常";

        UserInfoPO user = new UserInfoPO();
        user.setUsername(username);
        user.setPassword(password);
        user.setGender(gender);
        user.setBirthday(Date.valueOf(birthdayStr));
        user.setUserStatus(userStatus);

        // 插入数据库
        if (userInfoDAO.insertUser(user)) {
            out.write("{\"success\": true, \"message\": \"用户注册成功\"}");
        } else {
            out.write("{\"success\": false, \"message\": \"用户注册失败，可能用户名已存在\"}");
        }
        out.close();
    }
}
